package com.wlyy.his.ali.oss;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName AliOSSUtil
 * @Description TODO
 * @Author zhouyanhui
 * @Date 2021-09-02 19:13
 * @Version 1.0
 **/


@EnableConfigurationProperties(AliOssProperties.class)
public class AliOSSUtil {
    @Autowired
    private AliOssProperties aliOssProperties;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(AliOSSUtil.class);

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 删除
     *
     * @param fileKey
     * @return
     */
    public String deleteBlog(String fileKey) {
        LOGGER.info("=========>OSS文件删除开始");
        String endpoint = aliOssProperties.getEndpoint();
        String accessKeyId = aliOssProperties.getKeyid();
        String accessKeySecret = aliOssProperties.getKeysecret();
        String bucketName = aliOssProperties.getBucketname();
//        String fileHost = ossProperties.getFilehost();
        try {
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            if (!ossClient.doesBucketExist(bucketName)) {
                LOGGER.info("==============>您的Bucket不存在");
                return "您的Bucket不存在";
            } else {
                LOGGER.info("==============>开始删除Object");
                ossClient.deleteObject(bucketName, fileKey);
                LOGGER.info("==============>Object删除成功：" + fileKey);
                return "==============>Object删除成功：" + fileKey;
            }
        } catch (Exception ex) {
            LOGGER.info("删除Object失败", ex);
            return "删除Object失败";
        }
    }

    /**
     * 查询文件名列表
     *
     * @param bucketName
     * @return
     */
    public List<String> getObjectList(String bucketName) {
        List<String> listRe = new ArrayList<>();
        String endpoint = aliOssProperties.getEndpoint();
        String accessKeyId = aliOssProperties.getKeyid();
        String accessKeySecret = aliOssProperties.getKeysecret();
        try {
            LOGGER.info("===========>查询文件名列表");
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            //列出11111目录下今天所有文件
            listObjectsRequest.setPrefix("11111/" + format.format(new Date()) + "/");
            ObjectListing list = ossClient.listObjects(listObjectsRequest);
            for (OSSObjectSummary objectSummary : list.getObjectSummaries()) {
                System.out.println(objectSummary.getKey());
                listRe.add(objectSummary.getKey());
            }
            return listRe;
        } catch (Exception ex) {
            LOGGER.info("==========>查询列表失败", ex);
            return new ArrayList<>();
        }
    }


    public String uploadFile(MultipartFile file) {
        // 工具类获取值
        String endpoint = aliOssProperties.getEndpoint();
        System.out.println("3333333" + endpoint);
        String accessKeyId = aliOssProperties.getKeyid();
        String accessKeySecret = aliOssProperties.getKeysecret();
        String bucketName = aliOssProperties.getBucketname();
//        String fileHost = ossProperties.getFilehost();

        try {
            // 创建OSS实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();

            //1 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // yuy76t5rew01.jpg
            fileName = uuid + fileName;

            //2 把文件按照日期进行分类
            //获取当前日期
            //   2019/11/12
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            //  2019/11/12/ewtqr313401.jpg
            fileName =  datePath + "/" + fileName;

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //  https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}


